/**
 * 简化Phase 2 路由 - 用于调试
 * EndoSight-UC 医疗AI系统
 */

import express from 'express';
import {
  getVersion,
  getProcessStatus,
  healthCheck
} from '../controllers/phase2ControllerSimple.js';
import { authenticateToken } from '../middleware/auth.js';
import auditService from '../services/auditService.js';

const router = express.Router();

// 记录API访问的中间件
const logApiAccess = (req, res, next) => {
  const startTime = Date.now();

  res.on('finish', () => {
    const duration = Date.now() - startTime;

    auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'api_access',
      accessType: req.method.toLowerCase(),
      accessReason: `Phase 2 API访问: ${req.path}`,
      dataBefore: null,
      dataAfter: {
        path: req.path,
        method: req.method,
        statusCode: res.statusCode,
        duration: duration
      },
      phiPresent: false,
      consentVerified: false,
      accessGranted: true
    }).catch(error => {
      console.error('API访问日志记录失败:', error);
    });
  });

  next();
};

// 应用访问日志中间件
router.use(logApiAccess);

// 健康检查 (无需认证)
router.get('/health', healthCheck);

// 版本信息 (无需认证)
router.get('/version', getVersion);

// 进程状态 (需要认证)
router.get('/process/status', authenticateToken, getProcessStatus);

// 工作器状态 (需要认证) - 简化版
router.get('/workers/status', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: 'Phase 2 工作器状态获取成功 (简化模式)',
    data: {
      workers: {
        ai_inference: { active: 1, total: 1, status: 'healthy' },
        file_processing: { active: 1, total: 1, status: 'healthy' },
        cleanup: { active: 1, total: 1, status: 'healthy' },
        monitoring: { active: 1, total: 1, status: 'healthy' }
      },
      total_workers: 4,
      active_workers: 4,
      timestamp: new Date().toISOString()
    }
  });
});

// 队列监控 (需要认证) - 简化版
router.get('/queues/monitor', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: 'Phase 2 队列监控获取成功 (简化模式)',
    data: {
      queues: {
        ai_inference: { waiting: 0, active: 0, completed: 0, failed: 0 },
        file_processing: { waiting: 0, active: 0, completed: 0, failed: 0 },
        cleanup: { waiting: 0, active: 0, completed: 0, failed: 0 }
      },
      redis_status: 'degraded_mode',
      timestamp: new Date().toISOString()
    }
  });
});

// 增强推理 (需要认证) - 简化版
router.post('/scoring/enhanced-inference', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: 'Phase 2 增强推理提交成功 (简化模式)',
    data: {
      taskId: `phase2_task_${Date.now()}`,
      status: 'queued',
      priority: 'normal',
      estimatedTime: '3-5秒',
      message: '完整AI推理功能正在调试中，当前返回模拟响应',
      timestamp: new Date().toISOString()
    }
  });
});

// 性能指标 (需要认证) - 简化版
router.get('/metrics/performance', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: 'Phase 2 性能指标获取成功 (简化模式)',
    data: {
      system: {
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        cpu: 'N/A (Node.js limited)',
        status: 'healthy'
      },
      workers: {
        total: 4,
        active: 4,
        avg_response_time: '0.5s',
        success_rate: '99.5%'
      },
      queues: {
        total_tasks: 0,
        avg_wait_time: '0.1s',
        throughput: '10 tasks/min'
      },
      timestamp: new Date().toISOString()
    }
  });
});

export default router;